using System;
using System.Collections;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;

/****************************************************
// 功能：UI窗口基类帮助类
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/2/18 16:4:48
*****************************************************/

public partial class BaseWindow
{
    protected ResourceManager resource;
    protected NetManager net;
    protected ModelManager model;
    protected AudioManager audioManager;
    protected UIManager ui;

    /// <summary>
    /// 深度查找子对象transform引用
    /// </summary>
    /// <param name="root"></param>
    /// <param name="childName"></param>
    /// <returns></returns>
    protected Transform FindChildTransform(Transform root, string childName)
    {
        var result = root.Find(childName);
        if (result != null) return result;
        foreach (Transform item in root)
        {
            result = FindChildTransform(item, childName);
            if (result != null)
            {
                return result;
            }
        }

        return result;
    }
    
    protected void SetActive(Transform trans, bool state = true)
    {
        trans.gameObject.SetActive(state);
    }
    
    protected void SetActive(GameObject game, bool isActive = true)
    {
        game.SetActive(isActive);
    }

    protected void SetActive(Image img, bool state = true)
    {
        img.transform.gameObject.SetActive(state);
    }
    
    protected void SetActive(Text txt, bool state = true)
    {
        txt.transform.gameObject.SetActive(state);
    }
    protected void SetActive(InputField ipt, bool state = true) {
        ipt.gameObject.SetActive(state);
    }
    
    protected void SetText(Text txt, int num = 0) {
        SetText(txt, num.ToString());
    }
    protected void SetText(Text text, string content = "")
    {
        text.text = content;
    }
    
    protected void SetText(TMP_Text text, string content = "")
    {
        text.text = content;
    }

    protected void SetSprite(Button button, string path)
    {
        SetSprite(button.image, path);
    }

    protected void SetSprite(Image img, string path)
    {
        Sprite sprite = ResourceManager.Instance.LoadSprite(path, true);
        img.sprite = sprite;
    }

    protected IEnumerator SetDownImageToLocal(Image img, string url, string fileName)
    {
        var cacheDir = Path.Combine(Application.persistentDataPath, "ImageCache");
        if (!Directory.Exists(cacheDir)) Directory.CreateDirectory(cacheDir);
        fileName = fileName.GetHashCode() + ".png";
        var imagePath = Path.Combine(cacheDir, fileName);
        
        if (File.Exists(imagePath))
        {
            var data = File.ReadAllBytes(imagePath);
            var texture = new Texture2D(512, 515);
            if (texture.LoadImage(data))
            {
                img.sprite = Sprite.Create(texture, new Rect(0.0f,0.0f, texture.width, texture.height), Vector2.zero);
            }
            else
            {
                // 文件损坏、加载失败则删除损坏文件‌
                File.Delete(imagePath);
            }
            
        }
        else
        {
            var request = UnityWebRequestTexture.GetTexture(url);
            yield return request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"Error downloading image: {request.error}");
            }
            else
            {
                var texture = DownloadHandlerTexture.GetContent(request);
                img.sprite = Sprite.Create(texture, new Rect(0.0f,0.0f, texture.width, texture.height), Vector2.zero);
                var savePath = Path.Combine(cacheDir, fileName);
                var bytes = texture.EncodeToPNG();
                File.WriteAllBytes(savePath, bytes);
            }
            
        }
    }

    /// <summary>
    /// 下载视频到本地，断点传续
    /// </summary>
    /// <param name="web"></param>
    /// <param name="videoPlayer"></param>
    /// <param name="fileName"></param>
    /// <param name="time"></param>
    /// <returns></returns>
    protected IEnumerator SetDownViewPlayerToLocal(UnityWebRequest web, VideoPlayer videoPlayer, string fileName, double time = 0)
    {
        var cacheDir = Path.Combine(Application.persistentDataPath, "VideoCache");
        if (!Directory.Exists(cacheDir)) Directory.CreateDirectory(cacheDir);
        var videoPath = Path.Combine(cacheDir, fileName);
        
        var fileSize = File.Exists(videoPath) ? new FileInfo(videoPath).Length : 0;
        using (web)
        {
            // 设置断点续传请求头
            web.SetRequestHeader("Range", $"bytes={fileSize}-");
            
            // 配置文件流写入模式
            var downloadHandler = new DownloadHandlerFileStream(videoPath, fileSize);
            web.downloadHandler = downloadHandler;

            // 启动下载
            web.SendWebRequest();
            
            // 实时监测下载进度
            while (!web.isDone)
            {
                if (web.downloadedBytes > 0)
                {
                    // 初始化视频播放器
                    if (!videoPlayer.isPrepared)
                    {
                        InitializeVideoPlayer(videoPlayer, videoPath, time);
                        yield return WaitForVideoReady(videoPlayer);
                    }
                }
                yield return null;
            }
            
            if (web.isDone)
            {
                //Debug.Log("视频下载完成了:" + web.isDone);
                
                InitializeVideoPlayer(videoPlayer, videoPath, time);
                videoPlayer.Play(); 
            }




            // 错误处理、忽略416错误
            if (web.result != UnityWebRequest.Result.Success && web.responseCode != 416)
            {
                Debug.LogError($"视频下载失败: {web.error}");
            }
        }
    }
    
    private static void InitializeVideoPlayer(VideoPlayer videoPlayer, string videoPath, double time = 0)
    {
        videoPlayer.source = VideoSource.Url;
#if UNITY_ANDROID
        videoPlayer.url = "file://" + videoPath;
#else
        videoPlayer.url = videoPath;
#endif
        videoPlayer.errorReceived += (source, message) =>
        {
            // 解决 Invalid sample cursor 用到的折中方案
            double currentTime = videoPlayer.time;
            videoPlayer.Stop();
            videoPlayer.time = currentTime - 1;
            videoPlayer.Play();
        };
        if (time > 0) { videoPlayer.time = time; }
        videoPlayer.Prepare();
    }
    private static IEnumerator WaitForVideoReady(VideoPlayer videoPlayer)
    {
        while (!videoPlayer.isPrepared)
            yield return new WaitForSeconds(0.5f);
        
        videoPlayer.Play();
    }
    
    
    #region ClickEvents

    protected T GetOrAddCommpont<T>(GameObject game) where T : Component
    {
        T t = game.GetComponent<T>();
        if (t == null) { t = game.AddComponent<T>(); }

        return t;
    }
    
    protected void OnClick(GameObject game, Action<object[]> action, params object[] args) {
        Listener listener = GetOrAddCommpont<Listener>(game);
        listener.onClick = action;
        if (args != null) { listener.args = args; }
    }
    
    protected void OnClickDown(GameObject game, Action<PointerEventData> data)
    {
        Listener listener = GetOrAddCommpont<Listener>(game);
        listener.onClickDown = data;
    }
    protected void OnClickUp(GameObject game, Action<PointerEventData> data)
    {
        Listener listener = GetOrAddCommpont<Listener>(game);
        listener.onClickUp = data;
    }
    
    protected void OnDrag(GameObject game, Action<PointerEventData> data)
    {
        Listener listener = GetOrAddCommpont<Listener>(game);
        listener.onDrag = data;
    }

    #endregion
    
}
